package com.moodswings;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

/**
 * Detektuje trenutnu poziciju na osnovu raznih senzora
 */

public class PositionSense implements LocationListener {

	private final Context context;
	protected final Location defaultLocation;
	private LocationManager locationManager;
	private Location currentLocation;

	// ---------------------------------------------------------------- init

	public PositionSense(Context context, Location defaultLocation) {
		this.context = context;
		this.defaultLocation = defaultLocation;
	}

	public void init() {
		initLocationListeners();
	}


	/**
	 * Inicijalizuje GPS.
	 */
	private void initLocationListeners() {
		locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		//c.setBearingRequired(true);

		String bestProvider = locationManager.getBestProvider(criteria, true);
		try {
			currentLocation = new Location(locationManager.getLastKnownLocation(bestProvider));
		} catch (Exception ex) {
			currentLocation = defaultLocation;
		}

		locationManager.requestLocationUpdates(bestProvider, 500, 1, this);
	}

	/**
	 * Zatvara sve senzore
	 */
	public void close() {
		try {
			locationManager.removeUpdates(this);
		} catch (Exception ignore) {
		}
		locationManager = null;
	}

	// ---------------------------------------------------------------- gps

	/**
	 * Network location listener.
	 */
	public void onLocationChanged(Location location) {
		if (location == null) {
			return;
		}
		setLocation(location);
	}

	public void onStatusChanged(String s, int i, Bundle bundle) {
	}

	public void onProviderEnabled(String s) {
	}

	public void onProviderDisabled(String s) {
	}

	/**
	 * Postavlja trenutnu lokaciju
	 */
	protected void setLocation(Location location) {
		currentLocation = location;
	}

	/**
	 * Vraca trenutnu lokaciju
	 */
	public Location getLocation() {
		return currentLocation;
	}

}
